package com.example.demo.controller;

import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.util.JwtUtil;
import com.example.demo.util.UserConverter;
import com.example.demo.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户控制器
 * 
 * @author zhang
 * @date 2024
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public Result<UserVO> getCurrentUser(HttpServletRequest request) {
        try {
            String authHeader = request.getHeader("Authorization");
            String token = authHeader.substring(7); // 跳过 "Bearer "
            String username = jwtUtil.getUsernameFromToken(token);
            
            User user = userMapper.findByUsername(username);
            if (user == null) {
                return Result.create().error(404, "用户不存在");
            }
            
            UserVO userVO = UserConverter.toVO(user);
            return Result.create(userVO);
        } catch (Exception e) {
            logger.error("获取用户信息失败: {}", e.getMessage());
            return Result.create().error(500, e.getMessage());
        }
    }
    
    /**
     * 根据ID获取用户信息
     */
    @PostMapping("/detail")
    public Result<UserVO> getUserById(@RequestParam Long id) {
        try {
            User user = userMapper.findById(id);
            if (user == null) {
                return Result.create().error(404, "用户不存在");
            }
            
            UserVO userVO = UserConverter.toVO(user);
            return Result.create(userVO);
        } catch (Exception e) {
            logger.error("获取用户信息失败: {}", e.getMessage());
            return Result.create().error(500, e.getMessage());
        }
    }
}

